<?php
/**
 * Active.class.php
 *
 * @author 周剑锋 <camfee@foxmail.com>
 * @date   17-8-31 上午10:39
 *
 */

namespace controls\MobileApi\Center;

use Center\Active as CActive;
use Center\ActiveOffer;
use Center\CoinLog;
use Center\CouponConfig;
use Center\QrCode;
use Center\Shop;
use Center\User;
use Center\UserCoupon;
use Center\VoteActive;
use Center\VoteActiveInfo;
use MobileApi\ApiBase;

/**
 * 用户钱包相关
 *
 * @package Center
 * @author  周剑锋 <camfee@foxmail.com>
 * @since   v1.0.0   2017-11-25
 */
class Active extends ApiBase
{
    /**
     * 活动结果公示
     *
     * <pre>
     * GET:
     *      activeid: 必选, 活动id
     * </pre>
     *
     * @return void|string 返回JSON数据
     *
     * <pre>
     * {
     *     "Status": 200,
     *     "Result": {
     *         "Title": "活动结果公示标题",
     *         "Time": "2017－07-06  13:23",
     *         "WinList": [ // 获奖信息
     *             {
     *                 "UserId": 1,
     *                 "UserNick": "用户昵称", // 昵称
     *                 "Price": "￥6.00", // 出价
     *                 "Time": "2017-09-23 14:32"
     *             },...
     *         ],
     *         "MyOfferList": [ // 你的出价
     *             {
     *                 "UserId": 1,
     *                 "UserNick": "用户昵称",
     *                 "Price": "￥6.00",
     *                 "Time": "2017-09-23 14:32"
     *             },...
     *         ],
     *         "OfferList": [ // 所有出价
     *             {
     *                 "Num": "1人",
     *                 "Price": "￥6.00",
     *             },...
     *         ]
     *     },
     *     "ServerTime": 1511661622
     * }
     * 异常状态
     * 201: 参数错误
     *
     * </pre>
     */
    public function getResult()
    {
        $uid = $this->isLogin(false);
        $activeid = (int)$_GET['activeid'];
        $active = CActive::getInfoByIds($activeid);
        if (empty($active)) {
            $this->output(201, '参数错误');
        }
        $win_list_info = ActiveOffer::getWinList($activeid);
        $win_list = [];
        if (!empty($win_list_info['data'])) {
            $uids = [];
            foreach ($win_list_info['data'] as $v) {
                $uids[] = $v['UserId'];
            }
            $users = User::getInfoByIds($uids);
            foreach ($win_list_info['data'] as $v) {
                $win_list[] = [
                    'UserId' => $v['UserId'],
                    'UserNick' => (string)$users[$v['UserId']]['UserNick'],
                    'Price' => '￥' . $v['OfferPrice'],
                    'Time' => $v['CreateTime'],
                ];
            }
        }
        $my_offer_info = ActiveOffer::getMyList($activeid, $uid);
        $my_list = [];
        if (!empty($my_offer_info['data'])) {
            $user_info = User::getInfoByIds($uid);
            foreach ($my_offer_info['data'] as $v) {
                $my_list[] = [
                    'UserId' => $v['UserId'],
                    'UserNick' => (string)$user_info['UserNick'],
                    'Price' => '￥' . $v['OfferPrice'],
                    'Time' => $v['CreateTime'],
                ];
            }
        }
        $all_list_info = ActiveOffer::getAllList($activeid);
        $all_list = [];
        if (!empty($all_list_info['data'])) {
            foreach ($all_list_info['data'] as $v) {
                $all_list[] = [
                    'Num' => $v['Num'] . '人',
                    'Price' => '￥' . $v['OfferPrice'],
                ];
            }
        }
        $data = [
            'Title' => $active['Name'],
            'Time' => $active['CreateTime'],
            'WinList' => $win_list,
            'MyOfferList' => $my_list,
            'OfferList' => $all_list,
        ];

        $this->output(200, $data);
    }

    /**
     * 活动详情
     *
     * <pre>
     * GET:
     *      activeid: 必选, 活动id
     * </pre>
     *
     * @return void|string 返回JSON数据
     *
     * <pre>
     * {
     *     "Status": 200,
     *     "Result": {
     *         "ActiveId": 1, // 活动id
     *         "ActiveTitle": "活动标题", // 活动标题
     *         "MinPrice": "1000", // 最低价格
     *         "MaxPrice": "2000", // 最高价格
     *         "PriceType": 0, // 出价类型 0：元 1：角 2：分
     *         "ViewCount": 21, // 活动点击数
     *         "RemainTime": 1516558978, // 活动截止时间
     *         "MaxOffer": 1, // 最大参与次数
     *         "BannerUrl": "广告图地址",
     *         "ActiveRules": "活动规则：释权归＊＊＊" // 活动规矩
     *         "ActiveImgUrl": "http://img.jingounet.com/xxxx" // 活动内容图片
     *     },
     *     "ServerTime": 1511663112
     * }
     * 异常状态
     * 201: 参数错误
     * </pre>
     */
    public function getActiveInfo()
    {
        $activeid = (int)$_GET['activeid'];
        $active_info = CActive::getInfoByIds($activeid);
        if (empty($active_info)) {
            $this->output(201, '参数错误');
        }

        $data = [
            'ActiveId' => $activeid,
            'ActiveTitle' => $active_info['Name'],
            'MinPrice' => $active_info['MinPrice'],
            'MaxPrice' => $active_info['MaxPrice'],
            'PriceType' => $active_info['PriceType'],
            'ViewCount' => $active_info['ViewCount'],
            'RemainTime' => strtotime($active_info['EndTime']) > 0 ? strtotime($active_info['EndTime']) : 0,
            'MaxOffer' => (int)$active_info['MaxOffer'],
            'BannerUrl' => $active_info['Cover'],
            'ActiveRules' => $active_info['Rules'],
            'ActiveImgUrl' => $active_info['ImgUrl']
        ];
        //增加显示次数
        \Center\Active::update($activeid, ['ViewCount' => ['ViewCount', '+1']]);
        $this->output(200, $data);
    }

    /**
     * 参与活动
     *
     * <pre>
     * POST:
     *      active_id:   必选, 活动id
     *      offer_price: 可选, 出价 多个用半角逗号','分隔 offer_price与price_***必选其一 优先offer_price
     *      price_type:  可选, 出价类型 最小单位精确到 0:元 1：角 2分 默认0
     *      price_start: 可选, 起始出价
     *      price_end:   可选, 截止出价
     * </pre>
     *
     * @return void|string 返回JSON数据
     *
     * <pre>
     * {
     *     "Status": 200,
     *     "Result": {},
     *     "ServerTime": 1511663112
     * }
     * {
     *     "Status": 203,
     *     "Result": {
     *         "Data" => {
     *              "MaxNum":100, //本次参与次数上限
     *              "ValidNum":80, //剩余可参加次数
     *         },
     *     },
     *     "ServerTime": 1511663112
     * }
     * 异常状态
     * 201: 参数错误
     * 202：金果不足
     * 203：出价次数超过最大参与次数
     * 204：网络错误，请稍后再试
     * 205：已经出过此价格
     * </pre>
     */
    public function joinActive()
    {
        $uid = $this->isLogin(true);
        $active_id = (int)$_POST['active_id'];
        $price_type = (int)$_POST['price_type'];
        $offer_price = trim($_POST['offer_price']);
        $price_start = trim($_POST['price_start']);
        $price_end = trim($_POST['price_end']);

        $active_info = CActive::getInfoByIds($active_id);
        $user_info = User::getInfoByIds($uid);
        if (empty($active_info) || (empty($offer_price) && (empty($price_start) || empty($price_end)))) {
            $this->output(201, '参数错误');
        }
        $my_price = ActiveOffer::getMyList($active_id, $uid);
        $check_price = [];
        if (!empty($my_price['data'])) {
            foreach ($my_price['data'] as $v) {
                $check_price[$v['OfferPrice']] = $v;
            }
        }

        $times = 0;
        $add = [];
        $date_time = date('Y-m-d H:i:s');
        if (!empty($offer_price)) {
            if (isset($check_price[$offer_price])) {
                $this->output(205, '已经出过此价格');
            }

            if (strpos($offer_price, ',')) {
                $pri_arr = explode(',', $offer_price);
                $add = [];
                foreach ($pri_arr as $pri_k => $pri_v) {
                    $add[] = [
                        'ActiveId' => $active_id,
                        'UserId' => $uid,
                        'OfferPrice' => $pri_v,
                        'CreateTime' => date('Y-m-d H:i:s', time() + $pri_k),
                    ];
                    $times++;
                }
            } else {
                $times = 1;
                $add = [
                    'ActiveId' => $active_id,
                    'UserId' => $uid,
                    'OfferPrice' => $offer_price,
                    'CreateTime' => $date_time,
                ];
            }
        } elseif (!empty($price_start) && !empty($price_end)) {
            $price_seed = 1;
            if ($price_type == 1) {
                $price_seed = 0.1;
            } elseif ($price_type == 2) {
                $price_seed = 0.01;
            }
            if ($price_end < $price_start) {
                $price_end_tmp = $price_start;
                $price_start = $price_end;
                $price_end = $price_end_tmp;
            }

            for ($i = 0; $price_start + $i <= $price_end; $i += $price_seed) {
                if (!isset($check_price[$offer_price])) {
                    $times++;
                    $add[] = [
                        'ActiveId' => $active_id,
                        'UserId' => $uid,
                        'OfferPrice' => $price_start + $i,
                        'CreateTime' => $date_time,
                    ];
                }
            }
        } else {
            $this->output(201, '参数错误2');
        }
        $coin = $times * 1;
        if ($coin > $user_info['JCoin']) {
            $this->output(202, '金果不足');
        }
        if ($my_price['count'] + $coin > $active_info['MaxOffer']) {
            $data['ErrorMsg'] = '出价次数超过最大参与次数';
            $data['Data'] = [
                'MaxNum' => $active_info['MaxOffer'],
                'ValidNum' => max($active_info['MaxOffer'] - $my_price['count'], 0)
            ];
            $this->output(203, $data);
        }

        $res = User::updateJCoin($uid, -$coin);
        if ($res === false) {
            debug_log("UserId: {$uid}, Coin: {$coin}", JF_LOG_INFO);
            $this->output(205, '扣除金果失败');
        }
        CoinLog::addCoinLog($uid, $coin, CoinLog::TYPE_ACTIVE, false);
        //if ($times == 1) {
        // 可以批量添加
        $ret = ActiveOffer::add($add, true);
        //} else {
        //    $ret = ActiveOffer::adds($add, true);
        //}

        if ($ret === false) {
            $this->output(204, '网络错误，请稍后再试');
        }

        $this->output(200);
    }

    /**
     * 活动列表
     *
     * <pre>
     * GET:
     *      status: 必选, 活动状态 0：所有 1:待公布 2：已公布 默认0
     *      offset: 可选， 偏移量 默认0
     *      limit:  可选， 每次数量, 最高不超过20 默认20
     * </pre>
     *
     * @return void|string 返回JSON数据
     *
     * <pre>
     * {
     *     "Status": 200,
     *     "Result": {
     *         "Total": 11,
     *         "List": [
     *             {
     *                 "ActiveId": 1, // 活动id
     *                 "ActiveName": "活动名称", // 活动名称
     *                 "Status": 1,  // 活动状态 1：待发布 2：已发布
     *                 "RemainTime": 1516558978, // 活动截止时间
     *                 "IsReward": 1, // 是否获得商品
     *                 "MyOffer": [ // 我的出价
     *                     {
     *                         "Price": "¥599",
     *                         "Time": "09-09 23:23"
     *                     },
     *                     {
     *                         "Price": "¥599",
     *                         "Time": "09-09 23:23"
     *                     }
     *                 ]
     *             },...
     *         ]
     *     },
     *     "ServerTime": 1511665034
     * }
     * 异常状态
     * 201: 参数错误
     *
     * </pre>
     */
    public function getActiveList()
    {
        $uid = $this->isLogin(true);
        $user_info = User::getInfoByIds($uid);
        $city_id = (int)$user_info['CityId'];
        $status = (int)$_GET['status'];
        $offset = (int)$_GET['offset'];
        $limit = (int)$_GET['limit'];
        $offset = max(0, $offset);
        $limit = $limit < 1 ? 20 : min($limit, 20);

        $my_aids_info = ActiveOffer::getMyActive($uid);
        $my_aids = [];
        if (!empty($my_aids_info['data'])) {
            $my_aids = $my_aids_info['data'];
        }
        $list_info = CActive::getListByCity($city_id, $offset, $limit, $status, $my_aids);
        $list = $active_ids = [];
        if (!empty($list_info['data'])) {
            foreach ($list_info['data'] as $v) {
                $active_ids[$v['Id']] = $v['Id'];
            }
            $my_all_offer = ActiveOffer::getMyActivesOffers($active_ids, $uid);
            foreach ($list_info['data'] as $v) {
                $active_ids[$v['Id']] = $v['Id'];
                $list[] = [
                    'ActiveId' => $v['Id'],
                    'ActiveName' => $v['Name'],
                    'Status' => $v['Status'],
                    'RemainTime' => strtotime($v['EndTime']) > 0 ? strtotime($v['EndTime']) : 0,
                    'IsReward' => isset($my_all_offer['wins'][$v['Id']]) ? 1 : 0,
                    'MyOffer' => !empty($my_all_offer['offers'][$v['Id']]) ? $my_all_offer['offers'][$v['Id']] : []
                ];
            }
        }

        $data = [
            'Total' => (int)$list_info['count'],
            'List' => $list
        ];

        $this->output(200, $data);
    }

    /**
     * 扫一扫 http://api.feeqoo.com/qrcode.php?type=1
     *
     * <pre>
     * GET:
     *      type: 必选, 二维码类型 1:活动 2：电子券 3：会员价 4：用户金果榜领奖
     *      id:   必选, 类型id
     *      hash: 必选, 校验码
     *      time: 必选, 时间
     * </pre>
     *
     * @return void|string 返回JSON数据
     *
     * <pre>
     * {
     *     "Status": 200,
     *     "Result": {
     *         "Id": 0,
     *         "Type": 1,
     *         "Tab": "领取奖品",
     *         "ActiveName": "活动标题最多两行超过打点活动标题最多两行超过打点",
     *         "ImgUrl": ""
     *     },
     *
     *     "Result": {
     *         "Id": 0,
     *         "Type": 2,
     *         "Tab": "验证电子券",
     *         "CouponName": "电子券标题如海尔线下商场电子券最多两行超过打点",
     *         "CashNum": 500,
     *         "ValidText": "2017.12.1-2018.2.1期间使用"
     *     },
     *
     *     "Result": {
     *         "Id": 0,
     *         "Type": 3,
     *         "Tab": "新会员认证",
     *         "ShopName": "鄂尔多斯旗舰店店铺名最多三行鄂尔多斯旗舰店店铺名最多三行",
     *         "ImgUrl": ""
     *     },
     *
     *     "Result": {
     *         "Id": 0,
     *         "Type": 4,
     *         "Tab": "领取奖品",
     *         "ShopName": "金果3月［用户金果榜］的第三名"
     *     },
     *
     *     "ServerTime": 1514472906
     * }
     * 异常状态
     * 201: 参数错误
     * </pre>
     */
    public function scan()
    {
        $uid = $this->isLogin(true);
        $type = intval($_GET['type']);
        $id = intval($_GET['id']);
        $hash = trim($_GET['hash']);
        $userinfo = User::getUserById($uid);
        if ($userinfo['ShopId'] < 1) {
            $this->output(201, '扫码用户非商家用户！');
        }
        $code_id = (int)$_GET['id'];
        $code_info = QrCode::getInfoByIds($code_id);
        if (empty($code_info)) {
            $this->output(202, '二维码记录不存在');
        }
        if ($code_info['Status'] == 1) {
            $this->output(203, '已经验证过了');
        }
        $now = date('Y-m-d H:i:s');
        $checktime = date('Y-m-d H:i:s', strtotime('+3 day'));
        if ($checktime < $code_info['CreateTime']) {
            QrCode::update($code_id, ['Status' => 2, 'UpdateTime' => $now]);
            $this->output(204, '二维码已过期');
        }
        switch ($code_info['Type']) {
            case QrCode::TYPE_ACT:
                $act = \Center\Active::getInfoByIds($code_info['TypeId']);
                $data = [
                    'Id' => $id,
                    'Type' => $type,
                    'Tab' => '领取奖品',
                    'ActiveName' => $act['Name'],
                    'ImgUrl' => $act['Cover'],
                ];
                break;
            case QrCode::TYPE_COUPON:
                $coupon = CouponConfig::getInfoByIds($code_info['TypeId']);
                $data = [
                    'Id' => $id,
                    'Type' => $type,
                    'Tab' => '验证电子券',
                    'CouponName' => $coupon['Name'],
                    'CashNum' => $coupon['Value'],
                    'ValidText' => '有效期:[' . $coupon['StartTime'] . '-' . $coupon['EndTime'] . ']' ,
                ];
                break;
            case QrCode::TYPE_SHOP_CHAP:
                if ($userinfo['ShopId'] != $code_info['TypeId']) {
                    $this->output(205, '商家ID与二维码所属商家不符');
                }
                $shopinfo = Shop::getInfoByIds($userinfo['ShopId']);
                if ($shopinfo['MaxJCoin'] < ($shopinfo['JCoin'] + 2)) {
                    $this->output(206, '商家预支金果数已超额，不能进行验证');
                }
                $data = [
                    'Id' => $id,
                    'Type' => $type,
                    'Tab' => '新会员认证',
                    'ShopName' => $shopinfo['Name'],
                    'ImgUrl' => $shopinfo['Cover'],
                    ];
                break;
            case QrCode::TYPE_REWARD_COIN:
                $vai = VoteActiveInfo::getInfoByIds($code_info['TypeId']);
                $vote = VoteActive::getInfoByIds($vai['ActiveId']);
                $data = [
                    'Id' => $id,
                    'Type' => $type,
                    'Tab' => '领取奖品',
                    'ShopName' => $vote['Name'] . '［用户金果榜］的第' . $vai['RewardRank'] . '名',
                ];
                break;
        }

        $this->output(200, $data);
    }

    /**
     * 扫一扫验证
     *
     * <pre>
     * POST:
     *      id:   必选, 二维码id
     * </pre>
     *
     * @return void|string 返回JSON数据
     *
     * <pre>
     * {
     *     "Status": 200,
     *     "Result": {},
     *     "ServerTime": 1511665034
     * }
     * 异常状态
     * 201: 扫码用户非商家用户
     * 202: 二维码记录不存在
     * 203: 已经验证过了
     * 204: 二维码已过期
     * 205: 商家预支金果数已超额，赠送金果失败请联系商家
     * </pre>
     */
    public function check()
    {
        $uid = $this->isLogin(true);
        $userinfo = User::getUserById($uid);
        if ($userinfo['ShopId'] < 1) {
            $this->output(201, '扫码用户非商家用户！');
        }
        $code_id = (int)$_POST['id'];
        $code_info = QrCode::getInfoByIds($code_id);
        if (empty($code_info)) {
            $this->output(202, '二维码记录不存在');
        }
        if ($code_info['Status'] == 1) {
            $this->output(203, '已经验证过了');
        }
        $now = date('Y-m-d H:i:s');
        switch ($code_info['Type']) {
            case QrCode::TYPE_ACT:
                QrCode::update($code_id, ['Status' => 1, 'UpdateTime' => $now, 'Info' => '已领取']);
                break;
            case QrCode::TYPE_COUPON:
                //TODO 需判定数据是否正常
                QrCode::update($code_id, ['Status' => 1, 'UpdateTime' => $now, 'Info' => '已领取']);
                $this->output(200);
                break;
            case QrCode::TYPE_SHOP_CHAP:
                $shopinfo = Shop::getInfoByIds($userinfo['ShopId']);
                //商家发送值增加两个金果
                Shop::update($userinfo['ShopId'], ['JCoin' => ['JCoin', '+2']]);
                //给用户增加两个金果
                CoinLog::addCoinLog($code_info['UserId'], 2, CoinLog::TYPE_SCAN_QRCODE, true, $shopinfo['Id']);
                QrCode::update($code_id, ['Status' => 1, 'UpdateTime' => $now, 'ShopId' => $shopinfo['Id']]);
                break;
            case QrCode::TYPE_REWARD_COIN:
                QrCode::update($code_id, ['Status' => 1, 'UpdateTime' => $now, 'Info' => '已领取']);
                break;
        }

        $this->output();
    }
}